<template>
  <view class="station-detail-page">
    <view class="swiper-wrapper">
      <uni-swiper-dot :info="imgList" :current="current" field="url" @change="onSwiperChange" v-if="imgList.length > 0">
        <swiper :current="current" @change="onSwiperChange" circular autoplay>
          <swiper-item v-for="(item, idx) in imgList" :key="idx">
            <image :src="item.url" class="swiper-img" mode="aspectFill" />
          </swiper-item>
        </swiper>
      </uni-swiper-dot>
      <view class="no-image-placeholder" v-else>
        <text class="no-image-text">暂无图片</text>
      </view>
    </view>
    <station-card 
      :station="detailStation"
      :show-location-click="false"
      @card-click="handleCardClick"
    />
    <view class="station-item">
      <view class="fast-charge-badge">
        <view class="fast-charge-label">快充</view>
        <view class="fast-charge-value">
          <text>空闲{{ detailStation.fastRate || '暂无' }}</text>
          <!--to do 三角形-->
          <text class="power-text" @click="onPriceDetail">最大功率{{ detailStation.power || '暂无' }}KW &gt;</text>
        </view>
      </view>
    </view>
    <view class="station-item">
      <view style="flex:1">
        <view class="price-section-header">
          <text>
            <text class="price-section-title">充电价格</text>
            <text class="price-section-time">(11:00~17:59)</text>
          </text>
          <view class="price-section-detail" @click="showPriceDetail">价格详情 &gt;</view>
        </view>
        <view class="price-cards">
          <view class="price-card origin-price">
            <text class="price-card-label">原价</text>
            <view class="price-card-value">
              <text class="price-card-num">{{ detailStation.fee || '暂无' }}</text>
              <text class="price-card-unit">元/度</text>
            </view>
          </view>
          <!--to do VIP卡左上圆角因为切割有点不圆滑，需要调整-->
          <view class="price-card vip-price">
            <text class="price-card-label">VIP价</text>
            <view class="price-card-value">
              <text class="price-card-num">{{ detailStation.vipFee || '暂无' }}</text>
              <text class="price-card-unit">元/度起</text>
              <view class="price-card-btn" @click="openVip">开通</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="station-item">
      <view style="flex:1">
        <view class="price-section-header">
          <text>
            <text class="price-section-title">电桩信息</text>
          </text>
          <view class="price-section-detail" @click="onPriceDetail">查看更多 &gt;</view>
        </view>
        <scroll-view 
          scroll-y="true" 
          class="pile-list-container"
          :show-scrollbar="true"
          :enhanced="true"
          :bounces="false"
          @scrolltolower="loadMoreExternalPiles"
        >
          <view class="pile-info-row" v-for="(item, idx) in externalFilteredPileList" :key="item.code">
            <view
              class="pile-status-circle"
              :style="{ borderColor: item.status === '空闲' ? '#7ac143' : (item.status === '占用' ? '#bbb' : '#ff6b35') }"
            >
              <text
                class="pile-status-text"
                :style="{ color: item.status === '空闲' ? '#7ac143' : (item.status === '占用' ? '#bbb' : '#ff6b35') }"
              >
                {{ item.status }}
              </text>
            </view>
            <view class="pile-info-detail">
              <view class="pile-info-line">
                <text>枪编码</text>
                <text class="pile-info-bold">{{ item.code }}</text>
                <uni-icons type="copy" size="20" color="#666" @click="onCopyCode(item.code)" />
              </view>
              <view class="pile-info-line">
                <text>最大功率</text>
                <text class="pile-info-bold">{{ item.power }}</text>
              </view>
            </view>
          </view>
          
          <!-- 加载更多提示 -->
          <view class="external-load-more-container" v-if="externalFilteredPileList.length > 0">
            <view class="external-load-more-text" v-if="externalIsLoading">正在加载...</view>
            <view class="external-load-more-text" v-else-if="!externalHasMore">没有更多数据了</view>
            <view class="external-load-more-text" v-else>下滑加载更多</view>
          </view>
          
          <!-- 空状态 -->
          <view class="external-empty-container" v-if="externalFilteredPileList.length === 0 && !externalIsLoading">
            <text class="external-empty-text">暂无电桩信息</text>
          </view>
        </scroll-view>
      </view>
    </view>
    <view class="station-item">
      <view style="flex:1">
        <view class="price-section-header">
          <text>
            <text class="price-section-title">服务设施</text>
          </text>
        </view>
        <view class="facility-icons">
          <!-- 餐饮 -->
          <view class="facility-item">
            <image :src="hasFacility('餐饮') ? '/static/images/canyin.png' : '/static/images/canyin_n.png'" class="facility-icon" />
            <text>餐饮</text>
          </view>
          <!-- 便利店 -->
          <view class="facility-item">
            <image :src="hasFacility('便利店') ? '/static/images/bianlidian.png' : '/static/images/bianlidian_n.png'" class="facility-icon" />
            <text>便利店</text>
          </view>
          <!-- 卫生间 -->
          <view class="facility-item">
            <image :src="hasFacility('卫生间') ? '/static/images/wsj.png' : '/static/images/wsj_n.png'" class="facility-icon" />
            <text>卫生间</text>
          </view>
          <!-- 休息室 -->
          <view class="facility-item">
            <image :src="hasFacility('休息室') ? '/static/images/xiuxishi.png' : '/static/images/xiuxishi_n.png'" class="facility-icon" />
            <text>休息室</text>
          </view>
          <!-- 有人值守 -->
          <view class="facility-item">
            <image :src="hasFacility('有人值守') ? '/static/images/kanshou.png' : '/static/images/kanshou_n.png'" class="facility-icon" />
            <text>有人值守</text>
          </view>
        </view>
      </view>
    </view>
    <!--to do 扫码充电吸底栏-->
    
    <!-- 价格详情弹窗 -->
    <uni-popup ref="pricePopup" type="bottom" :maskClick="true" :animation="true" :safeArea="true">
      <view class="price-popup-content">
        <view class="price-popup-header">
          <text class="price-popup-title">价格详情</text>
          <uni-icons type="closeempty" size="20" color="#666" @click="hidePriceDetail" />
        </view>
        <!--to do padding: 30rpx 0; 改为margin,他占据了空间-->
        <view class="price-table">
          <view class="table-header">
            <view class="th time-col">充电时段</view>
            <view class="th type-col">类型</view>
            <view class="th price-col">价格<text class="unit">(元/度)</text></view>
            <view class="th equal-col">=</view>
            <view class="th power-col">电费<text class="unit">(元/度)</text></view>
            <view class="th plus-col">+</view>
            <view class="th service-col">服务费<text class="unit">(元/度)</text></view>
          </view>
          <view class="table-row" v-for="(item, index) in priceList" :key="index">
            <view class="lowest-tag" v-if="item.isLowest">全天最低</view>
            <view class="td time-col">{{ item.range }}</view>
            <view class="td type-col">
              <text class="vip-tag">VIP</text>
              <text class="price-type">原价</text>
            </view>
            <view class="td price-col">
              <text class="price-value">{{ item.vipPrice }}</text>
              <text class="original-price">{{ item.originalPrice }}</text>
            </view>
            <view class="td equal-col">=</view>
            <view class="td power-col">
              <text class="price-value">{{ item.vipPowerPrice }}</text>
              <text class="original-price">{{ item.originalPowerPrice }}</text>
            </view>
            <view class="td plus-col">+</view>
            <view class="td service-col">
              <text class="price-value">{{ item.vipServicePrice }}</text>
              <text class="original-price">{{ item.originalServicePrice }}</text>
            </view>
          </view>
        </view>
        <view class="price-notice">
          <uni-icons type="info" size="14" color="#999" />
          <text class="notice-text">平台会以您开启充电时价格详情进行计费，如价格详情在充电后发生变化，结算以价格详情快照为准。</text>
        </view>
      </view>
    </uni-popup>

    <!-- 电桩信息弹窗 -->
    <uni-popup ref="pileInfoPopup" type="bottom" :maskClick="true" :animation="true" :safeArea="true">
      <view class="pile-info-popup">
        <view class="pile-info-header">
          <text class="pile-info-title">电桩信息</text>
          <uni-icons type="closeempty" size="20" color="#666" @click="hidePileInfo" />
        </view>
        
        <!-- 筛选标签 -->
        <view class="filter-tabs">
          <view 
            class="filter-tab" 
            :class="{ active: selectedFilter === 'all' }"
            @tap="selectFilter('all')"
          >
            <text class="filter-label">全部</text>
            <text class="filter-count">{{ allPileList.length }}</text>
          </view>
          <view 
            class="filter-tab" 
            :class="{ active: selectedFilter === 'idle' }"
            @tap="selectFilter('idle')"
          >
            <text class="filter-label">空闲</text>
            <text class="filter-count">{{ idleCount }}</text>
          </view>
          <view 
            class="filter-tab" 
            :class="{ active: selectedFilter === 'fast' }"
            @tap="selectFilter('fast')"
          >
            <text class="filter-label">快充</text>
            <text class="filter-count">{{ fastCount }}</text>
          </view>
          <view 
            class="filter-tab" 
            :class="{ active: selectedFilter === 'slow' }"
            @tap="selectFilter('slow')"
          >
            <text class="filter-label">慢充</text>
            <text class="filter-count">{{ slowCount }}</text>
          </view>
        </view>
        
        <!-- 电桩列表 -->
        <scroll-view 
          scroll-y="true" 
          class="pile-list-scroll"
          @scrolltolower="loadMorePiles"
          :show-scrollbar="true"
          :enhanced="true"
          :bounces="false"
        >
          <view class="pile-info-row" v-for="(item, idx) in filteredPileList" :key="item.code">
            <view
              class="pile-status-circle"
              :style="{ borderColor: item.status === '空闲' ? '#7ac143' : (item.status === '占用' ? '#bbb' : '#ff6b35') }"
            >
              <text
                class="pile-status-text"
                :style="{ color: item.status === '空闲' ? '#7ac143' : (item.status === '占用' ? '#bbb' : '#ff6b35') }"
              >
                {{ item.status }}
              </text>
            </view>
            <view class="pile-info-detail">
              <view class="pile-info-line">
                <text>枪编码</text>
                <text class="pile-info-bold">{{ item.code }}</text>
                <uni-icons type="copy" size="20" color="#666" @click="onCopyCode(item.code)" />
              </view>
              <view class="pile-info-line">
                <text>最大功率</text>
                <text class="pile-info-bold">{{ item.power }}</text>
              </view>
            </view>
          </view>
          
          <!-- 加载更多提示 -->
          <view class="load-more-container" v-if="filteredPileList.length > 0">
            <view class="load-more-text" v-if="isLoading">正在加载...</view>
            <view class="load-more-text" v-else-if="!hasMore">没有更多数据了</view>
            <view class="load-more-text" v-else>下滑加载更多</view>
          </view>
          
          <!-- 空状态 -->
          <view class="empty-pile-container" v-if="filteredPileList.length === 0 && !isLoading">
            <text class="empty-pile-text">暂无电桩信息</text>
          </view>
        </scroll-view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue'
import uniSwiperDot from '@/uni_modules/uni-swiper-dot/components/uni-swiper-dot/uni-swiper-dot.vue'
import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
import { getStationDetail } from '@/api/charging/index.js'
import { getStationFeeDetail } from '@/api/charging/index.js'
import StationCard from '@/components/station-card/index.vue' // 引入StationCard组件
import locationManager from '@/utils/location.js' // 引入位置管理器

export default {
  components: {
    uniPopup,
    uniSwiperDot,
    uniIcons,
    StationCard // 注册StationCard组件
  },
  data() {
    return {
      current: 0,
      imgList: [
      ],
      detailStation: {
        id: '',
        name: '',
        distance: '',
        facilities: '',
        price: '',
        status: 'available',
        availableCount: 0,
        totalCount: 0,
        businessTime: '',
        address: '',
        shopName: '',
        fastRate: '',
        parkFee: '',
        fee: '',
        electricityFee: '',
        serviceFee: '',
        vipFee: '',
        stationLat: '',
        stationLng: '',
        dist: '',
        shopId: '',
        slowRate: '',
        power: '',
        busineHours: '',
        pictures: [],
        connectors: [],
        facilityList: [] // 新增facilityList字段
      },
      pileList: [
        { status: '空闲', code: '12269225', power: '120kW' },
        { status: '占用', code: '12269226', power: '90kW' },
        { status: '80%', code: '12269227', power: '60kW' }
      ],
      priceList: [
        {
        }
      ],
      facilityIconMap: { // 设施名称到图标的映射字典
        '地上': 'shop',
        '卫生间': 'shop', 
        '快餐': 'shop',
        '便利店': 'shop'
      },
      selectedFilter: 'all', // 筛选标签的当前选中状态
      filteredPileList: [], // 根据筛选条件过滤后的电桩列表
      idleCount: 0, // 空闲电桩数量
      fastCount: 0, // 快充电桩数量（暂时为0，接口还区分不了）
      slowCount: 0, // 慢充电桩数量（暂时为0，接口还区分不了）
      // 分页相关属性
      pageSize: 20, // 每页显示数量
      currentPage: 1, // 当前页码
      hasMore: true, // 是否还有更多数据
      isLoading: false, // 是否正在加载
      allPileList: [], // 所有电桩数据（用于筛选）
      // 外部电桩信息列表分页属性
      externalPageSize: 5, // 外部列表每页显示数量
      externalCurrentPage: 1, // 外部列表当前页码
      externalHasMore: true, // 外部列表是否还有更多数据
      externalIsLoading: false, // 外部列表是否正在加载
      externalFilteredPileList: [] // 外部列表筛选后的电桩列表
    }
  },
  onLoad(options) {
    console.log('充电站详情页面接收到的参数:', options);
    
    // 接收传递的 station 数据
    if (options.stationData) {
      try {
        const stationData = JSON.parse(decodeURIComponent(options.stationData));
        console.log('解析后的充电站数据:', stationData);
        
        // 获取经纬度（从缓存或传入数据）
        const userLocation = locationManager.getCurrentLocation();
        const stationLat = userLocation.latitude;
        const stationLng = userLocation.longitude;
        const stationId = stationData.id || stationData.stationId;
        
        // 调用充电站详情接口
        this.getStationDetailData(stationId, stationLat, stationLng);
        // 价格详情
        this.loadStationFeeDetail({ stationId });
        
        // 初始化外部电桩信息列表（使用默认数据）
        this.initExternalPileList();
        
      } catch (error) {
        console.error('解析充电站数据失败:', error);
        uni.showToast({
          title: '数据解析失败',
          icon: 'none'
        });
      }
    } else {
      // 如果没有传入数据，尝试从options中获取stationId
      const stationId = options.stationId;
      if (stationId) {
        const userLocation = locationManager.getCurrentLocation();
        const stationLat = userLocation.latitude;
        const stationLng = userLocation.longitude;
        this.getStationDetailData(stationId, stationLat, stationLng);
        this.loadStationFeeDetail({ stationId });
      }
    }
  },
  mounted() {
    // 确保popup组件已经准备好
    setTimeout(() => {
      if (this.$refs.pricePopup) {
        console.log('价格弹窗组件已加载');
      }
    }, 100);
  },
  methods: {
    // 获取充电站详情数据
    getStationDetailData(stationId, stationLat, stationLng) {
      console.log('获取充电站详情，参数:', { stationId, stationLat, stationLng });
      
      getStationDetail({
        stationId: stationId,
        stationLat: stationLat,
        stationLng: stationLng
      }).then(response => {
        console.log('充电站详情接口响应:', response);
        
        if (response.code === 0 && response.success) {
          const data = response.data;
          
          // 更新详情数据
          this.detailStation = {
            id: data.stationId || '',
            name: data.stationName || '暂无',
            distance: data.dist ? `${data.dist}km` : '暂无',
            facilities: data.facilities || '暂无',
            price: data.fee ? data.fee.toString() : '暂无',
            status: 'available',
            availableCount: 0,
            totalCount: 0,
            businessTime: data.busineHours || '暂无',
            address: data.address || '暂无',
            shopName: data.shopName || '',
            fastRate: data.fastRate || '暂无',
            parkFee: data.parkFee || '暂无',
            fee: data.fee || '',
            electricityFee: data.electricityFee || '',
            serviceFee: data.serviceFee || '',
            vipFee: data.vipFee || '',
            stationLat: data.stationLat || '',
            stationLng: data.stationLng || '',
            dist: data.dist || '',
            shopId: data.shopId || '',
            slowRate: data.slowRate || '',
            power: data.power || '',
            busineHours: data.busineHours || '',
            pictures: data.pictures || [],
            connectors: data.connectors || [],
            facilityList: data.facilityList || [] // 更新facilityList
          };
          
          // 更新轮播图数据
          if (data.pictures && data.pictures.length > 0) {
            this.imgList = data.pictures.map(url => ({ url }));
          }
          
          // 更新电桩列表数据
          if (data.connectors && data.connectors.length > 0) {
            this.pileList = data.connectors.map(connector => ({
              status: connector.status || '未知',
              code: connector.connectorId || '',
              power: connector.power ? `${connector.power}kW` : ''
            }));
            
            // 初始化筛选数据
            this.selectedFilter = 'all';
            this.filterPileList();
            
            // 初始化外部电桩信息列表
            this.initExternalPileList();
          } else {
            // 如果没有电桩数据，也要初始化外部列表（使用默认数据）
            this.initExternalPileList();
          }
          
          console.log('更新后的详情数据:', this.detailStation);
        } else {
          uni.showToast({
            title: response.msg || '获取充电站详情失败',
            icon: 'none'
          });
        }
      }).catch(error => {
        console.error('获取充电站详情失败:', error);
        uni.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      });
    },
    onSwiperChange(e) {
      this.current = e.detail.current;
    },
    onPriceDetail() {
      // 打开电桩信息弹窗
      this.showPileInfo();
    },
    onCopyCode(code) {
      uni.setClipboardData({
        data: code,
        success: () => {
          uni.showToast({ title: '已复制', icon: 'none' });
        }
      });
    },
    showPriceDetail() {
      if(this.$refs.pricePopup) {
        console.log('打开价格详情弹窗');
        this.$refs.pricePopup.open('bottom');
      } else {
        console.log('价格弹窗组件未找到');
      }
    },
    hidePriceDetail() {
      if(this.$refs.pricePopup) {
        this.$refs.pricePopup.close();
      }
    },
    // 筛选电桩列表
    selectFilter(filterType) {
      this.selectedFilter = filterType;
      // 重置分页状态
      this.currentPage = 1;
      this.hasMore = true;
      // 重新筛选和分页
      this.filterPileList();
    },
    // 过滤电桩列表
    filterPileList() {
      // 先根据筛选条件过滤
      let filtered = this.allPileList.filter(item => {
        if (this.selectedFilter === 'all') {
          return true;
        }
        if (this.selectedFilter === 'idle') {
          return item.status === '空闲';
        }
        // 快充和慢充筛选暂时不生效，因为接口还区分不了
        if (this.selectedFilter === 'fast') {
          return false; // 暂时返回空数组
        }
        if (this.selectedFilter === 'slow') {
          return false; // 暂时返回空数组
        }
        return false;
      });
      
      // 应用分页
      this.applyPaginationAndFilter(filtered);
      
      // 更新筛选标签的计数
      this.updateFilterCounts();
    },
    
    // 应用分页和筛选
    applyPaginationAndFilter(filteredList = null) {
      let filtered = filteredList;
      if (!filtered) {
        // 如果没有传入过滤后的列表，重新过滤
        filtered = this.allPileList.filter(item => {
          if (this.selectedFilter === 'all') {
            return true;
          }
          if (this.selectedFilter === 'idle') {
            return item.status === '空闲';
          }
          // 快充和慢充筛选暂时不生效，因为接口还区分不了
          if (this.selectedFilter === 'fast') {
            return false; // 暂时返回空数组
          }
          if (this.selectedFilter === 'slow') {
            return false; // 暂时返回空数组
          }
          return false;
        });
      }
      
      // 计算总数和分页
      const total = filtered.length;
      const startIndex = 0;
      const endIndex = this.currentPage * this.pageSize;
      
      // 获取当前页的数据
      this.filteredPileList = filtered.slice(startIndex, endIndex);
      
      // 判断是否还有更多数据
      this.hasMore = endIndex < total;
      
      console.log(`分页信息: 当前页${this.currentPage}, 每页${this.pageSize}, 总数${total}, 当前显示${this.filteredPileList.length}, 还有更多: ${this.hasMore}`);
    },
    
    // 应用外部电桩信息列表的分页和筛选
    applyExternalPaginationAndFilter(allPiles) {
      // 计算总数和分页
      const total = allPiles.length;
      const startIndex = 0;
      const endIndex = this.externalCurrentPage * this.externalPageSize;
      
      // 获取当前页的数据
      this.externalFilteredPileList = allPiles.slice(startIndex, endIndex);
      
      // 判断是否还有更多数据
      this.externalHasMore = endIndex < total;
      
      console.log(`外部电桩分页信息: 当前页${this.externalCurrentPage}, 每页${this.externalPageSize}, 总数${total}, 当前显示${this.externalFilteredPileList.length}, 还有更多: ${this.externalHasMore}`);
      
      // 如果当前页没有数据，重置到第一页
      if (this.externalFilteredPileList.length === 0 && this.externalCurrentPage > 1) {
        this.externalCurrentPage = 1;
        this.applyExternalPaginationAndFilter(allPiles);
      }
    },
    // 更新筛选标签的计数
    updateFilterCounts() {
      // 添加调试日志，查看实际的状态数据
      const statusCounts = {};
      this.allPileList.forEach(item => {
        statusCounts[item.status] = (statusCounts[item.status] || 0) + 1;
      });
      console.log('电桩状态统计:', statusCounts);
      
      // 统计各种状态的数量
      this.idleCount = this.allPileList.filter(item => item.status === '空闲').length;
      
      // 快充和慢充暂时设为0，因为接口还区分不了
      this.fastCount = 0;
      this.slowCount = 0;
      
      console.log('筛选标签计数 - 全部:', this.allPileList.length, '空闲:', this.idleCount, '快充:', this.fastCount, '慢充:', this.slowCount);
    },
    // 关闭电桩信息弹窗
    hidePileInfo() {
      if(this.$refs.pileInfoPopup) {
        this.$refs.pileInfoPopup.close();
      }
    },
    // 显示电桩信息弹窗
    showPileInfo() {
      if(this.$refs.pileInfoPopup) {
        console.log('打开电桩信息弹窗');
        this.$refs.pileInfoPopup.open('bottom');
        // 初始化筛选数据
        this.selectedFilter = 'all';
        // 重置分页状态
        this.currentPage = 1;
        this.hasMore = true;
        this.isLoading = false;
        // 初始化电桩列表
        this.initPileList();
        // 立即更新筛选标签的计数，确保弹窗打开时就显示正确的统计
        this.updateFilterCounts();
      } else {
        console.log('电桩信息弹窗组件未找到');
      }
    },
    
    // 初始化电桩列表
    initPileList() {
      // 从detailStation.connectors获取电桩数据
      if (this.detailStation.connectors && this.detailStation.connectors.length > 0) {
        this.allPileList = this.detailStation.connectors.map(connector => ({
          status: connector.status || '未知',
          code: connector.connectorId || '',
          power: connector.power ? `${connector.power}kW` : ''
        }));
      } else {
        // 如果没有数据，使用默认数据
        this.allPileList = [
          { status: '空闲', code: '12269225', power: '120kW' },
          { status: '占用', code: '12269226', power: '90kW' },
          { status: '80%', code: '12269227', power: '60kW' }
        ];
      }
      
      // 立即更新筛选标签的计数
      this.updateFilterCounts();
      
      // 应用分页和筛选
      this.applyPaginationAndFilter();
    },
    
    // 初始化外部电桩信息列表
    initExternalPileList() {
      // 从detailStation.connectors获取电桩数据
      if (this.detailStation.connectors && this.detailStation.connectors.length > 0) {
        const allPiles = this.detailStation.connectors.map(connector => ({
          status: connector.status || '未知',
          code: connector.connectorId || '',
          power: connector.power ? `${connector.power}kW` : ''
        }));
        
        // 应用外部列表的分页和筛选
        this.applyExternalPaginationAndFilter(allPiles);
      } else {
        // 如果没有数据，使用默认数据
        const defaultPiles = [
          { status: '空闲', code: '12269225', power: '120kW' },
          { status: '占用', code: '12269226', power: '90kW' },
          { status: '80%', code: '12269227', power: '60kW' },
          { status: '空闲', code: '12269228', power: '120kW' },
          { status: '占用', code: '12269229', power: '90kW' },
          { status: '80%', code: '12269230', power: '60kW' }
        ];
        
        this.applyExternalPaginationAndFilter(defaultPiles);
      }
      
      // 确保统计数据是最新的
      this.updateFilterCounts();
    },
    // 加载场站价格详情
    loadStationFeeDetail(params) {
      const stationId = params && params.stationId ? params.stationId : (this.detailStation.id || this.detailStation.name);
      if (!stationId) {
        console.error('场站标识不存在，无法加载价格详情');
        return;
      }
      getStationFeeDetail({ stationId }).then(response => {
        console.log('详情页-场站价格详情响应:', response);
        if (response.code === 0 && response.success && Array.isArray(response.data)) {
          const mapped = response.data.map(item => ({
            range: item.rangeTime || '',
            vipPrice: item.vipFee || '',
            originalPrice: item.fee || '',
            vipPowerPrice: item.vipPrice || '',
            originalPowerPrice: item.price || '',
            vipServicePrice: item.vipServiceFee || '',
            originalServicePrice: item.serviceFee || '',
            isLowest: String(item.lowest) === 'true'
          }));

          let lowestIndex = mapped.findIndex(x => x.isLowest);
          if (lowestIndex === -1 && mapped.length > 0) {
            let min = Number.MAX_VALUE;
            mapped.forEach((x, i) => {
              const v = parseFloat(x.vipPrice) || Number.MAX_VALUE;
              if (v < min) { min = v; lowestIndex = i; }
            });
            if (lowestIndex !== -1) mapped[lowestIndex].isLowest = true;
          }

          this.priceList = mapped;
        } else {
          uni.showToast({ title: response.msg || '加载价格详情失败', icon: 'none' });
        }
      }).catch(error => {
        console.error('详情页-加载场站价格详情接口失败:', error);
        uni.showToast({ title: error.msg || '网络请求失败', icon: 'none' });
      });
    },
    // 加载更多电桩数据
    loadMorePiles() {
      if (!this.hasMore || this.isLoading) {
        return;
      }
      
      this.isLoading = true;
      console.log('开始加载更多电桩数据，当前页:', this.currentPage);
      
      // 模拟异步加载延迟
      setTimeout(() => {
        // 增加页码
        this.currentPage++;
        
        // 重新应用分页和筛选
        this.applyPaginationAndFilter();
        
        this.isLoading = false;
        console.log('加载更多完成，当前页:', this.currentPage, '是否还有更多:', this.hasMore);
      }, 500);
    },
    // 加载更多外部电桩数据
    loadMoreExternalPiles() {
      if (!this.externalHasMore || this.externalIsLoading) {
        return;
      }
      
      this.externalIsLoading = true;
      console.log('开始加载更多外部电桩数据，当前页:', this.externalCurrentPage);
      
      // 模拟异步加载延迟
      setTimeout(() => {
        // 增加页码
        this.externalCurrentPage++;
        
        // 重新应用分页和筛选
        this.initExternalPileList();
        
        this.externalIsLoading = false;
        console.log('加载更多完成，当前页:', this.externalCurrentPage, '是否还有更多:', this.externalHasMore);
      }, 500);
    },
    openVip() {
      uni.showToast({
        title: '暂未实现vip相关功能',
        icon: 'none'
      });
    },
    // 判断设施是否存在
    hasFacility(facilityName) {
      if (!this.detailStation.facilityList || !Array.isArray(this.detailStation.facilityList)) {
        return false;
      }
      // 如果facilityList是字符串数组，直接比较字符串
      if (typeof this.detailStation.facilityList[0] === 'string') {
        return this.detailStation.facilityList.includes(facilityName);
      }
      // 如果facilityList是对象数组，比较name字段
      return this.detailStation.facilityList.some(facility => 
        facility.name === facilityName || facility === facilityName
      );
    },
    // 处理站点卡片点击事件
    handleCardClick() {
      console.log('站点卡片被点击');
      // 可以在这里跳转到地图页面，并传递站点信息
      uni.navigateTo({
        url: `/pages/map/index?stationId=${this.detailStation.id}&stationName=${this.detailStation.name}&stationLat=${this.detailStation.stationLat}&stationLng=${this.detailStation.stationLng}`
      });
    },
    
    // 文字截断方法
    truncateText(text, maxLength) {
      if (!text || text.length <= maxLength) {
        return text;
      }
      return text.substring(0, maxLength) + '...';
    }
  }
}
</script>

<style scoped>
.station-detail-page {
  background: #fbfbfb;
  min-height: 100vh;
  padding: 0;
}
.swiper-wrapper {
  background: #fff;
  border-radius: 18rpx;
  padding: 20rpx;
  margin: 20rpx auto;
  box-shadow: 0 4rpx 16rpx rgba(255, 153, 0, 0.08);
}
.swiper-img {
  width: 100%;
  height: 300rpx;
  display: block;
  border-radius: 12rpx;
}
.no-image-placeholder {
  width: 100%;
  height: 300rpx;
  background: #f5f5f5;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx dashed #ddd;
}
.no-image-text {
  font-size: 28rpx;
  color: #999;
}
.station-jam {
  background: linear-gradient(180deg, #b97a56 0%, #eac9b0 100%);
  border-bottom-right-radius: 16rpx;
  padding: 0 24rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: -5rpx;
  left: -5rpx;
}
.station-jam-text {
  color: #fff;
  font-size: 22rpx;
  font-weight: bold;
}
.station-item {
  width: 85%;
  margin: 20rpx auto 20rpx auto;
  background: #fff;
  border-radius: 18rpx;
  box-shadow: 0 4rpx 16rpx rgba(255, 153, 0, 0.08);
  padding: 30rpx;
  display: flex;
  position: relative;
}
.station-info {
  flex: 1;
}
.station-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}
.station-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}
.station-distance {
  display: flex;
  align-items: center;
  border: 1rpx solid #e5e5e5;
  border-radius: 24rpx;
  padding: 4rpx 8rpx;
}
.distance-text {
  font-size: 24rpx;
  color: #666;
}
.station-details {
  margin-bottom: 15rpx;
}
.station-facilities {
  font-size: 24rpx;
  color: #666;
}
.station-business-time {
  margin-top: 10rpx;
  display: flex;
  align-items: center;
}
.business-time-label {
  font-size: 24rpx;
  color: #666;
  margin-right: 10rpx;
}
.business-time-text {
  font-size: 24rpx;
  color: #333;
  font-weight: bold;
}
.station-address {
  margin-top: 10rpx;
  display: flex;
  align-items: center;
}
.address-label {
  font-size: 24rpx;
  color: #666;
  margin-right: 10rpx;
}
.address-text {
  font-size: 24rpx;
  color: #333;
  font-weight: bold;
}
.station-pricing {
  display: flex;
  align-items: baseline;
}
.price-label {
  font-size: 24rpx;
  color: #ff6b35;
}
.price-amount {
  font-size: 36rpx;
  font-weight: bold;
  color: #ff6b35;
}
.price-unit {
  font-size: 24rpx;
  color: #ff6b35;
  margin-right: 20rpx;
}
.station-rating {
  display: flex;
  align-items: center;
  background: none;
  padding: 0;
  margin-top: 10rpx;
}
.station-rating-icon {
  width: 36rpx;
  height: 36rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(90deg, #bfc3c9 0%, #e6e8eb 100%);
  margin-right: 0;
}
.station-rating-rateIcon{
  width: 36rpx;
  height: 36rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(90deg, #ff6b35 0%, #ffb59a 100%);
  margin-right: 0;
}
.station-rating-p {
  color: #fff;
  font-weight: bold;
  font-size: 24rpx;
}
.station-rating-rate {
  color: #fff;
  font-size: 20rpx;
  font-weight: bold;
}
.station-rating-text-bg {
  background: #f5f6f7;
  border-radius: 0 8rpx 8rpx 0;
  padding: 0 12rpx;
  height: 36rpx;
  display: flex;
  align-items: center;
}
.station-rating-text-numBg{
  background: #fff7f5;
  border-radius: 0 8rpx 8rpx 0;
  padding: 0 12rpx;
  height: 36rpx;
  display: flex;
  align-items: center;
}
.station-rating-text {
  color: #888;
  font-size: 22rpx;
}
.station-rating-text-num {
  color: #ff6b35;
  font-size: 20rpx;
  font-weight: bold;
}
.station-status {
  display: flex;
  align-items: center;
  margin-left: auto;
}
.member-price-badge {
  display: inline-flex;
  align-items: center;
  height: 36rpx;
  border-radius: 8rpx;
  overflow: hidden;
}
.member-price-label {
  background: #ff6b35;
  color: #fff;
  font-size: 18rpx;
  font-weight: bold;
  padding: 0 12rpx;
  height: 36rpx;
  display: flex;
  align-items: center;
  border-radius: 8rpx 0 0 8rpx;
  box-sizing: border-box;
}
.member-price-value {
  position: relative;
  background: #fff;
  color: #ff6b35;
  font-size: 18rpx;
  font-weight: bold;
  padding: 0 16rpx;
  height: 36rpx;
  display: flex;
  align-items: center;
  border-radius: 0 8rpx 8rpx 0;
  border: 2rpx solid #ff6b35;
  border-left: none;
  box-sizing: border-box;
}
.member-price-value::before {
  content: '';
  position: absolute;
  left: -12rpx;
  top: 0;
  width: 24rpx;
  height: 36rpx;
  background: #fff;
  border-radius: 18rpx 0 0 18rpx;
  z-index: 1;
}
.station-item-with-shop {
  position: relative;
}
.station-item-with-shop::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 1rpx;
  height: 100%;
  background: linear-gradient(to bottom, rgba(234, 201, 188, 1), rgba(232, 207, 188, 0.3));
}
.station-item-with-shop::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 1rpx;
  background: linear-gradient(to right, rgba(185, 122, 86, 1), rgba(232, 207, 188, 0.3));
}
.fast-charge-badge {
  display: inline-flex;
  align-items: center;
  height: 54rpx;
  border-radius: 8rpx;
  overflow: hidden;
  flex: 1;
}
.fast-charge-label {
  background: #ff6b35;
  color: #fff;
  font-size: 28rpx;
  font-weight: bold;
  padding: 0 12rpx;
  height: 54rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx 0 0 8rpx;
  box-sizing: border-box;
  flex: 0.2;
}
.fast-charge-value {
  position: relative;
  background: #fff;
  font-size: 28rpx;
  font-weight: bold;
  padding: 0 16rpx;
  height: 54rpx;
  display: flex;
  align-items: center;
  border-radius: 0 8rpx 8rpx 0;
  border: 2rpx solid #ff6b35;
  border-left: none;
  box-sizing: border-box;
  flex: 0.8;
  padding-left: 20rpx;
}
.power-text {
  font-size: 20rpx;
  margin-left: auto;
  color: #666;
  cursor: pointer;
  transition: color 0.3s ease;
}

.power-text:hover {
  color: #ff6b35;
}

.power-text:active {
  color: #e55a2b;
}
.price-section {
  margin-top: 20rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 18rpx;
  box-shadow: 0 4rpx 16rpx rgba(255, 153, 0, 0.08);
}
.price-section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}
.price-section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}
.price-section-time {
  font-size: 24rpx;
  color: #666;
  margin-right: 20rpx;
  margin-left: 20rpx;
}
.price-section-detail {
  font-size: 24rpx;
  color: #666;
  display: flex;
  align-items: center;
  margin-left: auto;
}
.price-cards {
  display: flex;
  justify-content: space-between;
  gap: 8rpx;
}

.price-card {
  flex: 1;
  background: linear-gradient(135deg, #fff9f0 0%, #fff7e6 100%);
  border-radius: 20rpx;
  padding: 24rpx 28rpx 24rpx 28rpx;
  display: flex;
  flex-direction: column;
  box-shadow: none;
  min-width: 0;
}

.origin-price {
  flex: 3.5;
  /* 右侧向左倾斜 */
  /*clip-path: polygon(0 0, 100% 0%, 98% 100%, 0% 100%);*/
}

.vip-price {
  flex: 6.5;
  /* 左侧向右倾斜 */
  /*clip-path: polygon(2% 0, 100% 0, 100% 100%, 0% 100%);*/
}

.price-card-label {
  font-size: 24rpx;
  color: #ff6b35;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.vip-price .price-card-label {
  color: #333;
}

.price-card-value {
  display: flex;
  align-items: baseline;
  gap: 8rpx;
}

.price-card-num {
  font-size: 36rpx;
  font-weight: bold;
  color: #ff6b35;
}

.vip-price .price-card-num {
  color: #333;
}

.price-card-unit {
  font-size: 22rpx;
  color: #999;
}

.price-card-btn {
  background: linear-gradient(90deg, #ffe0b2 0%, #ffd180 100%);
  color: #333;
  font-size: 22rpx;
  font-weight: bold;
  padding: 4rpx 22rpx;
  border-radius: 32rpx;
  margin-left: 16rpx;
  box-shadow: none;
  display: flex;
  align-items: center;
  justify-content: center;
}
.pile-info-row {
  display: flex;
  align-items: center;
  margin: 20rpx 0;
}
.pile-list-container {
  max-height: 450rpx;
}
.pile-status-circle {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  border: 4rpx solid #7ac143;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
}
.pile-status-text {
  color: #7ac143;
  font-size: 22rpx;
}
.pile-info-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.pile-info-line {
  display: flex;
  align-items: center;
  margin-bottom: 6rpx;
}
.pile-info-bold {
  font-weight: bold;
  margin: 0 8rpx;
}
.facility-icons {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  margin-top: 20rpx;
}
.facility-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 10rpx 15rpx;
}
.facility-item uni-icons {
  margin-bottom: 8rpx;
}
.facility-item text {
  font-size: 20rpx;
  color: #666;
}
.facility-item image {
  width: 64rpx; /* 调整图片大小 */
  height: 64rpx; /* 调整图片大小 */
  margin-bottom: 12rpx; /* 调整图片间距 */
  border-radius: 8rpx; /* 添加圆角 */
}

.price-popup-content {
  background-color: #fff;
  padding: 30rpx;
  width: 100%;
  box-sizing: border-box;
  border-radius: 24rpx 24rpx 0 0;
}

.price-popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0 30rpx;
  border-bottom: 1rpx solid #eee;
}

.price-popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.price-table {
  padding: 20rpx 0;
  width: 95%;
  margin: 0 auto;
}

.table-header {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  font-size: 24rpx;
  color: #666;
  text-align: center;
}

.table-row {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  height: 60rpx;
  font-size: 24rpx;
  color: #333;
  text-align: center;
  border-bottom: 1rpx solid #f5f5f5;
  position: relative;
}

.lowest-tag {
  position: absolute;
  top: 18rpx;
  left: 0rpx;
  background: #ff6b35;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
  transform: translateY(-50%);
}

.th, .td {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.time-col {
  flex: 2;
  text-align: left;
}

.type-col {
  flex: 1.5;
}

.price-col, .power-col, .service-col {
  flex: 1.5;
}

.equal-col, .plus-col {
  flex: 0.5;
}

.unit {
  font-size: 20rpx;
  color: #999;
  margin-left: 4rpx;
}

.vip-tag {
  background: #ff6b35;
  color: #fff;
  font-size: 20rpx;
  padding: 2rpx 8rpx;
  border-radius: 4rpx;
  margin-bottom: 4rpx;
}

.price-type {
  color: #999;
  font-size: 20rpx;
}

.price-value {
  color: #ff6b35;
  font-weight: bold;
  margin-bottom: 4rpx;
}

.original-price {
  color: #999;
  font-size: 20rpx;
  text-decoration: line-through;
}

.price-notice {
  display: flex;
  align-items: flex-start;
  padding: 20rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
  margin-top: 30rpx;
}

.notice-text {
  font-size: 22rpx;
  color: #999;
  line-height: 1.4;
  margin-left: 8rpx;
  flex: 1;
}

.pile-info-popup {
  background-color: #fff;
  padding: 30rpx;
  width: 100%;
  height: 70vh;
  box-sizing: border-box;
  border-radius: 24rpx 24rpx 0 0;
  display: flex;
  flex-direction: column;
}

.pile-info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0 30rpx;
  border-bottom: 1rpx solid #eee;
}

.pile-info-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.filter-tabs {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20rpx;
  padding: 0 10rpx;
}

.filter-tab {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10rpx 20rpx; /* 调整水平内边距 */
  border-radius: 32rpx;
  margin: 0 8rpx; /* 调整标签间距 */
  flex: 1; /* 让四个标签平均分配空间 */
  max-width: 150rpx; /* 限制最大宽度 */
}

.filter-tab.active {
  color: #333;
  border-color: #ff6b35;
}

.filter-label {
  font-size: 24rpx;
  font-weight: bold;
  margin-bottom: 4rpx;
}

.filter-count {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: 20rpx;
  color: #999;
  min-width:80rpx;
  border-radius: 16rpx;
  background: transparent;
}

.filter-tab.active .filter-count {
  background: #ff6b35;
  color: #fff;
}

.pile-list-scroll {
  flex: 1;
  overflow-y: auto;
}

.load-more-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 24rpx;
}

.empty-pile-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 28rpx;
}

.load-more-text {
  text-align: center;
  color: #999;
  font-size: 24rpx;
}

.external-load-more-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 24rpx;
}

.external-empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 28rpx;
}

.external-load-more-text {
  text-align: center;
  color: #999;
  font-size: 24rpx;
}
</style> 